import { defineStore } from 'pinia'
import { getLeagues, getSports, getSportsRegions, getHotLeagues } from '@/api/betting'
import { useAppStore } from './app'
import { SportsType } from '@/enums'
import { enumList, getSportsIcon, getSportsCode, getTextTById, getTextById } from '@/utils'
import { LeagueType, SportsDetailDialog } from '@/types'

export const useSportsStore = defineStore('sports', {
	state: () => ({
		sports: [],
		recommedLeagueIds: [] as string[],
		regions: [] as any[],
		hotLeagues: [] as LeagueType[],
		liveEventId: '',
		detailDialog: {} as SportsDetailDialog
	}),
	actions: {
		async getSports() {
			const appStore = useAppStore()
			try {
				const { data } = await getSports({
					page: 1,
					pageSize: 100,
					locale: appStore.lang,
					location: appStore.region
				})
				this.sports = data.list
			} catch {}
		},
		async getRecommendLeagues() {
			const appStore = useAppStore()
			try {
				const { data } = await getLeagues({
					page: 1,
					pageSize: 1000,
					locale: appStore.lang,
					location: appStore.region,
					isRecommend: true
				})
				this.recommedLeagueIds = data.list.map((item: any) => item.leagueId)
			} catch {}
		},
		async getRegions(sportId = '') {
			const appStore = useAppStore()
			try {
				const { data } = await getSportsRegions({
					page: 1,
					sportId: sportId,
					locale: appStore.lang,
					location: appStore.region
				})
				this.regions = data.list
			} catch {}
		},
		async getHotLeagues() {
			const appStore = useAppStore()
			try {
				const { data } = await getHotLeagues({
					locale: appStore.lang,
					oddsStyle: appStore.odds,
					location: appStore.region
				})
				this.hotLeagues = data.list
			} catch {}
		},
		async setLiveStream(eventId: string) {
			this.liveEventId = eventId
		},
		async setDetail(val: SportsDetailDialog) {
			this.detailDialog = val
		}
	},
	getters: {
		groupRegions(state) {
			const res: any = {}
			state.regions.forEach((item: any) => {
				const { regionCode } = item
				const key = regionCode[0]
				if (res[key]) {
					res[key].push(item)
				} else {
					res[key] = [item]
				}
			})
			return res
		},
		sportList(state) {
			const res: any[] = []
			const supportTypes = enumList(SportsType)
			const supportTypeIds = supportTypes.map(({ id }) => id)
			state.sports.forEach((item) => {
				const { sportId } = item
				if (supportTypeIds.indexOf(sportId) !== -1) {
					res.push({
						id: sportId,
						code: getSportsCode(sportId),
						icon: getSportsIcon(sportId),
						textT: getTextTById(supportTypes, sportId),
						text: getTextById(supportTypes, sportId)
					})
				}
			})
			return res
		},
		isRecommedLeagues(state) {
			return (leagueId: string) => state.recommedLeagueIds.includes(leagueId)
		}
	},
	persist: true
})
